<template>
  <section class="income">

    <header>
      <div class="acount">
        <img src="../../../static/images/u347.png" alt="">
        <div class="header-detail">
          <div>账上余额</div>
          <div>￥{{incomeMessage.balance}}</div>
        </div>
      </div>
      <div class="pay">
        <img src="../../../static/images/u328.png" alt="">
        <div class="header-detail">
          <div>年度总支出</div>
          <div>￥{{incomeMessage.total_expenditure}}</div>
        </div>
      </div>
      <div class="income">
        <img src="../../../static/images/u332.png" alt="">
        <div class="header-detail">
          <div>年度总收入</div>
          <div>￥{{incomeMessage.total_income}}</div>
        </div>
      </div>
    </header>


    <el-col :span="24" class="action-bar">
      <span class="task-form-text">收支：</span>
      <el-select v-model="searchType" class="action-bar-input" placeholder="请选择">
        <el-option
          v-for="item in searchTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-col :span="10" class="action-bar-searchtime" :offset="1">
        <el-col :span="11">
          <el-date-picker type="datetime" placeholder="选择开始日期" value-format="yyyy-MM-dd HH:mm:ss" v-model="searchTime.start" style="width: 100%;"></el-date-picker>
        </el-col>
        <el-col class="line" :span="2" >-</el-col>
        <el-col :span="11">
          <el-date-picker placeholder="选择结束时间" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" v-model="searchTime.end" style="width: 100%;"></el-date-picker>
        </el-col>
      </el-col>
			<el-button type="primary" size="medium" @click="search">筛选</el-button>
      <el-button type="primary" size="medium" @click="newIncome">新增</el-button>
      <el-button type="primary" size="medium" @click="exportExcelAll">全部导出</el-button>
    </el-col>

    <el-col :span="24" class="action-bar search-result" v-if="searchFlag">
      <h3>筛选结果汇总<el-button type="primary" size="medium" @click="exportExcelPart" style="margin-left:20px;">导出</el-button></h3>
      <div>{{incomeMessage.page_info.start_time}}&nbsp;&nbsp;到&nbsp;&nbsp;{{incomeMessage.page_info.end_time}}</div>
      <div>总收入&nbsp;￥{{incomeMessage.page_info.filter_income}}</div>
      <div>总支出&nbsp;￥{{incomeMessage.page_info.filter_expenditure}}</div>
    </el-col>
    <!--列表-->


		<el-table :data="incomeList" highlight-current-row class="el-table-style">
			<el-table-column type="selection" width="55"/>
			<el-table-column type="index" width="60"/>
			<el-table-column prop="name" label="名称" width="120"/>
			<el-table-column prop="account_type" label="类别" width="100">
        <template slot-scope="scope">
          <div>
            <span v-show="scope.row.account_type==0">收入</span>
            <span v-show="scope.row.account_type==1">支出</span>
          </div>
        </template>
      </el-table-column>
			<el-table-column prop="created_at" label="收支时间" width="180"/>
			<el-table-column prop="account_amount" label="金额" width="120"/>
			<el-table-column prop="manager" label="经办人" width="180"/>
      <el-table-column prop="remarks" label="备注" width="180"/>
			<el-table-column label="操作" width="250">
				<template slot-scope="scope">
          <div>
            <el-button type="primary" size="mini" @click="editorIncome(scope.row.id)">编辑</el-button>
          </div>
        </template>
			</el-table-column>
		</el-table>
		<el-col :span="24" class="footer-bar">
			<div class="page-code">
        <el-pagination
					background
					:page-size="16"
					layout="prev, pager, next"
					:total="totalPage"
					@current-change="pageChange"
						>
				</el-pagination>
      </div>
    </el-col>

    <!-- 弹出的编辑窗口 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      height="50%"
      center
      class="editor-dialog"
      :title="dialogTit"
      @close="closeDialog" 
      >
      
      <el-form :label-position="'left'" label-width="80px" :model="member" >
        <el-form-item label="名称">
          <el-input v-model="member.name"></el-input>
        </el-form-item>
        <el-form-item label="收支类型">
          <el-select v-model="member.payType" placeholder="请选择">
            <el-option
              v-for="item in payTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收支时间">
          <el-date-picker
            v-model="member.incomeTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="金额">
          <el-input v-model="member.money" type="number"></el-input>
        </el-form-item>
        <el-form-item label="经办人">
          <el-input v-model="member.operator"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="member.remarks"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setAccountFlow" v-if="newIncomeFlag">提交</el-button>
        <el-button type="primary" @click="setAccountFlow" v-else>提交</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
	data(){
		return {
      incomeMessage:'',//头部的信息
			incomeList:[

      ],
      dialogTit:'',
      newIncomeFlag:'',//区分新增还是编辑
      dialogVisible:false,//编辑状态的弹窗
      searchType:'',//筛选的状态
      searchTypeOptions:[
        {label:'全部',value:''},
        {label:'收入',value:0},
        {label:'支出',value:1},
      ],
      searchTime:{//筛选的时间区域
        start:'',
        end:this.$currency.formatDateTime(new Date())
      },
      payTypeOptions:[//收支类型
        {label:'收入',value:0},
        {label:'支出',value:1}
      ],
      member:{
        name:'',
        payType:'',//收支类型
        incomeTime:'',//收支时间
        money:'',//金额
        operator:'',//经办人
        remarks:''//备注
      },//弹窗的信息
      page:1,
      totalPage:0,
      id:'',//数据的id
      searchFlag:false,//搜索结果是否显示
		}
  },
  methods: {
    editor(){
      //对缴费用户进行编辑
      this.dialogVisible = true
    },
    handleClose(){
      //编辑弹窗关闭前的回调

    },
    search(){
      this.page=1;
      this.accountFlowList();
      if(this.searchTime.start ||this.searchTime.end){
        this.searchFlag=true;//显示筛选结果
      }else{
        this.searchFlag=false
      }
    },
    async accountFlowList(){
      //获取收支管理
      const res=await this.$api.accountFlowList({
        page:this.page,
        account_type:this.searchType,
        start_time:this.searchTime.start,
        end_time:this.searchTime.end
      })
      if(res.data.level=='success'){
        this.incomeList=res.data.data.data
        this.totalPage=res.data.data.total;
        this.incomeMessage=res.data;
      }else{
        this.$message({
          type:'error',
          message:res.data.message
        })
      }
    },
    pageChange(e){
			//翻页
			this.page=e;
			this.accountFlowList()
		},
    newIncome(){
      //新增
      this.dialogTit='新增';
      this.newIncomeFlag=true;
      this.id='';
      this.dialogVisible=true;
    },
    editorIncome(id){
      //编辑
      this.dialogTit='编辑';
      this.newIncomeFlag=false;
      this.id=id;
      this.accountFlowSet()
      this.dialogVisible=true;
    },
    async setAccountFlow(){
      //设置收支管理
      const res=await this.$api.setAccountFlow({
        name:this.member.name,
        manager:this.member.operator,
        account_type:this.member.payType,
        remarks:this.member.remarks,
        account_amount:this.member.money,
        id:this.id,
        created_at:this.member.incomeTime
      })

      if(res.data.level=='success'){
            this.$message({
                message: res.data.message,
                type: 'success'
                });
                this.page=1;
                this.accountFlowList()
            this.dialogVisible=false;
        }else{
            this.$message({
            message: res.data.message,
            type: 'error'
            });
        }
    },
    async accountFlowSet(){
      //收支管理信息
      const res=await this.$api.accountFlowSet({
        id:this.id
      })
      if(res.data.level=='success'){
        const data=res.data.data
        this.member.name=data.name;
        this.member.payType=+data.account_type;
        this.member.incomeTime=data.created_at;
        this.member.operator=data.manager;
        this.member.remarks=data.remarks;
        this.member.money=data.account_amount;
      }
    },
    exportExcelAll(){
      //导出全部
		const judge= this.$confirm('导出会员信息？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
				}).then(async() => {
					//获取无分页收支管理
            const res=await this.$api.accountFlowList({
            })
					if(res.data.level=='success'){
            let data=res.data.excel_data;
						this.exportExcelHandle(data);
						this.$message({
							type: 'success',
							message: res.data.message
						});
					}else{
						this.$message({
							type: 'error',
							message: res.data.message
						});
					}
					
				}).catch(() => {
          
			});
  },
  exportExcelPart(){
      //导出
		const judge= this.$confirm('导出会员信息？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
				}).then(async() => {
					//获取无分页收支管理
            const res=await this.$api.accountFlowList({
              account_type:this.searchType,
              start_time:this.searchTime.start,
              end_time:this.searchTime.end
            })
					if(res.data.level=='success'){
            let data=res.data.excel_data;
						this.exportExcelHandle(data);
						this.$message({
							type: 'success',
							message: res.data.message
						});
					}else{
						this.$message({
							type: 'error',
							message: res.data.message
						});
					}
					
				}).catch(() => {
          
			});
  },
	exportExcelHandle(data){
    let res=data.map((item)=>{
      let obj={};
      obj['名称']=item.name;
      if(item.account_type==0){
        obj['类别']='收入'
      }else{
        obj['类别']='支出'
      }
      obj['收支时间']=item.recording_time;
      obj['金额']=item.account_amount;
      obj['经办人']=item.manager;
      obj['备注']=item.remarks;
      return obj
    })
		// let data = [
    //         {name: "张三", id: "123"},
    //         {name: "李四", id: "124"}
    //     ];
    
		 let ws = XLSX.utils.json_to_sheet(res);
        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "收支");
        var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
         try {
             FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
         } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
         return wbout
	},
    closeDialog(){
      this.member.name='';
        this.member.payType='';
        this.member.incomeTime='';
        this.member.operator='';
        this.member.remarks='';
        this.member.money='';
    },
  },
  mounted() {
    this.accountFlowList()
  },
}
</script>
<style lang='scss' scoped>
  .income{
    header{
      display: flex;
      align-items: center;
      justify-content: space-around;
      font-size: 25px;
      &>div{
        display: flex;
        img{
          width: 60px;
          height: 60px;
          margin:0 20px;
        }
        align-items: center;
        justify-content: center;
      }
    }
    .task-form-text{
				color: #666666;
			}
    .action-bar{
			background-color: #f2f2f2;
			height: 60px;
      margin: 10px 0px;
      box-sizing: border-box;
			display: flex;
			align-items: center;
      flex-wrap: wrap;
			padding-left: 20px;
			.action-bar-input{
				width: 250px;
				margin-right: 14px;
      }
      .action-bar-searchtime{
        margin-right: 30px;
        .line{
          line-height:40px;
          text-align:center;
        }
      }
		}
    .search-result{
      height: auto !important;
      padding:10px;
      font-size: 16px;
      color:#606266;
        div{
          width: 100%;
          margin:10px 0;
        }
      }
		.el-table-style{
			width: 100%;
			border: 1px solid #f2f2f2;
		}
		.footer-bar{
			display: flex;
			justify-content: space-between;
			align-items: center;
      background: #f2f2f2;
      padding: 8px;
      margin: 10px 0px;
      box-sizing: border-box;
		}
		.dialog-footer{
			text-align: center;
		}
  }
</style>

<style>
	
	.el-pagination.is-background .el-pager li,
	.el-pagination.is-background .btn-prev,
	.el-pagination.is-background .btn-next
	{
		background-color: #fff;
		border: 1px solid #f1f1f1;
		margin: 0;
	}

 .income .el-dialog__body{overflow: auto;}
</style>
